# BSD3.0
# cili@163.com

import tkinter as tk
from tkinter import filedialog
import base64
from tkinter import messagebox


class ImageEncoder:
    def __init__(self, root):
        self.root = root
        self.root.title("图像编码转换器")
        self.create_widgets()
        self.center_window()

    def create_widgets(self):
        buttons_value = [('选择图像', self.process_image), ('复制代码', self.copy_to_clipboard)]
        self.buttons = [tk.Button(self.root, text=bv[0], command=bv[1]) for bv in buttons_value]
        [button.grid(row=0, column=index, padx=10, pady=5) for index, button in enumerate(self.buttons)]
        self.base64_text = tk.Text(self.root, height=15, width=80, wrap='char')
        self.base64_text.grid(row=2, column=0, columnspan=2, padx=5, pady=10)
        self.buttons[-1].config(state='disable')

    def center_window(self):
        self.root.update()
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = self.root.winfo_width()
        window_height = self.root.winfo_height()
        x = int((screen_width / 2) - (window_width / 2))
        y = int((screen_height / 2) - (window_height / 2))
        self.root.geometry(f'{window_width}x{window_height}+{x}+{y}')

    def encode_image_to_base64(self, image_path):
        with open(image_path, "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read())
            return '<img src="data:image/jpeg;base64,' + encoded_string.decode('utf-8') + '" alt="Image"/>'

    def process_image(self):
        file_path = filedialog.askopenfilename()
        if file_path:
            base64_string = self.encode_image_to_base64(file_path)
            self.base64_text.delete('1.0', tk.END)
            self.base64_text.insert(tk.END, base64_string)
            self.buttons[-1].config(state="normal")  # 生成base64代码后，启用复制按钮

    def copy_to_clipboard(self):
        base64_string = self.base64_text.get("1.0", tk.END).strip()
        self.root.clipboard_clear()
        self.root.clipboard_append(base64_string)
        self.root.update()
        messagebox.showinfo("复制成功", "Base64字符串已复制到粘贴板")


if __name__ == "__main__":
    root = tk.Tk()
    app = ImageEncoder(root)
    root.mainloop()
